from aiogram import Router, F
from aiogram.filters import StateFilter
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import StatesGroup, State
from aiogram.types import Message
from keyboards.set_menu import just_keyboard, cancel_keyboard

from db.PGConnector import PGFamily, PGUser
from .utils import try_except_decorator

router = Router()

def is_exist_func(family_name, user_id):
    pg_family = PGFamily()
    is_exist = pg_family.is_family_name_exists(family_name, user_id)
    return is_exist

class BotState(StatesGroup):
    creating_family_name = State()


@router.message(StateFilter(None), F.text == "Создать семью")
async def cmd_create(message: Message, state: FSMContext):
    await message.answer(text="Напишите название семьи", reply_markup=cancel_keyboard())
    await state.set_state(BotState.creating_family_name)


@try_except_decorator
@router.message(BotState.creating_family_name)
async def created_family(message: Message, state: FSMContext):
    await state.update_data(family_name=message.text)

    family = await state.get_data()
    family_name = family['family_name'].strip()

    user_id = message.chat.id
    nickname = message.chat.username

    pg_user = PGUser()
    pg_user.create_user(user_id, nickname)

    pg_family = PGFamily()
    family_created = pg_family.create_family(family_name, user_id)

    if family_created:
        await message.answer(text=f'✅ Семья "{family_name}" успешно создана.', reply_markup=just_keyboard())
        await state.clear()
    elif len(family_name) > 100:
        await message.answer(text='❗️Название семьи должно быть до 100 символов.', reply_markup=cancel_keyboard())
    elif is_exist_func(family_name, user_id):
        await message.answer(text='❗️Семья с таким названием уже существует.', reply_markup=cancel_keyboard())
    else:
        await message.answer(text='❗️Не удалось создать семью с таким именем. Убедитесь, '
                                  'что вы не состоите в семье с таким именем.', reply_markup=cancel_keyboard())
